import React, { useEffect, useMemo, useRef, useState } from 'react'
import style from '../xiaoxi/index.module.css'
import { Button, Input, Toast, Image } from 'antd-mobile'
function Index() {
    const user_id = 1;
    const server_id = 7788;
    const [list, setList] = useState([]);
    const [message, setMessage] = useState('');
    const refMsg = useRef(null)

    const ws = useMemo(() => {
        return new WebSocket(
            `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
        );
    }, [])

    useEffect(() => {
        ws.onopen = () => {
            console.log('ok');
            ws.send(JSON.stringify({ type: 'getChatList' }))
        };

        ws.onmessage = (msg) => {
            console.log(msg.data);
            const { data, type } = JSON.parse(msg.data)
            if (type === 'getChatList') {
                setList(data)
            } else if (type === 'AddMessage') {
                setList((prev) => [...prev, data])
            }
        }
    }, [])

    useEffect(() => {
        refMsg.current.scrollIntoView({
            behavior: 'auto'
        })
    }, [list])


    const send = ()=>{
        if(!message) return Toast.show('请输入内容')

            ws.send(JSON.stringify({
                type:'AddMessage',
                data:{
                    user_id,
                    server_id,
                    message
                }
            }))
            setMessage('')
    }
    return (
        <div>
            <div>

                <div className={style.msgBox}>
                    {list.length > 0 && list.map((item, index) => {
                        if (item.dir === 1) {
                            return <div className={style.right} key={index}>
                                <Image style={{ width: '50px', height: '50px', borderRadius: '50%' }} src={item.user_avatar} className={style.img}></Image>

                                <div className={style.tit}>
                                    {item.message}
                                </div>
                            </div>
                        }
                    })}
                </div>
                <div ref={refMsg} />

                <div className={style.sendBox}>

                    <Input
                        className={style.inp}
                        placeholder='请输入内容'
                        value={message}
                        onChange={val => {
                            setMessage(val)
                        }}
                    />


                    <Button onClick={()=>send()} className={style.btn} color='primary' fill='solid'>
                        发送
                    </Button>


                </div>

            </div>

        </div>
    )
}

export default Index
